package cn.honqun.tinycms.controller;

import cn.honqun.tinycms.common.dto.Page;
import cn.honqun.tinycms.domain.copier.RoleCopier;
import cn.honqun.tinycms.domain.entity.Role;
import cn.honqun.tinycms.domain.vo.RoleVO;
import cn.honqun.tinycms.service.RoleService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author catstiger
 * @since 2024-02-07
 */
@RestController
@RequestMapping("/admin/role")
@RequiredArgsConstructor
public class RoleController {
    private final RoleService roleService;

    /**
     * 新增或者跟新角色
     */
    @PostMapping("/saveOrUpdate")
    public Role saveOrUpdate(@RequestBody @Valid RoleVO roleVO) {
        Role role = RoleCopier.INSTANCE.toRoleBO(roleVO);
        roleService.saveOrUpdate(role);

        return role;
    }

    @GetMapping("/selectById")
    public RoleVO selectById(Long id) {
        Role role = roleService.getById(id);
        return RoleCopier.INSTANCE.toRoleVO(role);
    }

    @GetMapping("/select")
    public Page<Role> select(Page<Role> page, RoleVO roleVO) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>(Role.class).select()
                .like(StrUtil.isNotBlank(roleVO.getRole()), Role::getRole, roleVO.getRole())
                .like(StrUtil.isNotBlank(roleVO.getName()), Role::getName, roleVO.getName());

        return roleService.page(page, queryWrapper);
    }

    @GetMapping("/list")
    public List<Role> list() {
        return roleService.list();
    }

    @PostMapping("/remove")
    public Boolean remove(@RequestBody RoleVO roleVO) {
        return roleService.removeById(roleVO);
    }
}
